/**
 * author:Administrator
 * date:2016/3/19
 * desc: 订单支付
 * -> 源事件 Order: paid
 * ->on orderPaid => Ticket : create
 */

'use strict';

let Saga = require('../../lib/Saga.js');
let events = require('./domainEvent.js');
let Ticket = require('../model_cmd/ticket/Ticket.js');
let OrderRepo = require('../model_cmd/order/OrderRepo.js');
let Order = require('../model_cmd/order/Order.js');

let debug = console.log.bind(console);

class OrderSaga extends Saga {
  constructor(order) {
    super();
    debug(this.constructor.name + ' set up...');
    super.subscribe(events.ENUM_EVENT.orderPaid);
    this.order = order;
  }

  // 启动
  * start() {
    yield this.order.pay(this.sagaId);
  }

  * orderPaid(event) {
    debug('handle event ', event.type);
    let order = event.data; // outdate, need reload it
    let orderPojo = yield OrderRepo.find(order.id);
    order = Order.rebuild(orderPojo);
    let ticket = Ticket.fromPaidOrder(order, this.sagaId);
    yield ticket.store(this.sagaId);

    this._end(order);
  }

  /** 返回结果 */
  * result() {
    let self = this;
    return new Promise(function (fulfil, reject) {
      self.fulfil = fulfil;
    });
  }
}

module.exports = OrderSaga;